import { VueObj } from "../main";
//export const webSocket = new WebSocket("ws://52.77.238.82:10112/StrategyControl");
export const webSocket = new WebSocket("ws://13.250.29.220:10112/StrategyControl");
/**
 * webstock连接成功
 */
webSocket.onopen = function() {
        console.log("websocket open------------------------------------------");
        VueObj.$eventHub.$emit('webSocketInit', "true");
        /*  let obj = {"requestType": "login"}
          webstock.send(JSON.stringify(obj))*/
        // let obj={
        //     op:"status",
        //     token:"9983e30f476dd007b833e566a717f455",
        //     userid:"MajorShi",
        //     strategyid:"02190325092944248777",
        //     data:null
        // };
        // webstock.send(JSON.stringify(obj));
    }
    /**
     * webstock接收消息
     */
webSocket.onmessage = function(message) {
    if(!isJson(message.data)){
        return;
    }
    let data=JSON.parse(message.data);
    console.log("接收的消息",data);
    VueObj.$eventHub.$emit(data.op, data);

}


/**
 * webstock关闭
 */
webSocket.onclose = function() {
        console.log("WebSocket close");
    }
    /**
     * webstock出错
     */
webSocket.onerror = function() {
    VueObj.$eventHub.$emit('webSocketError', "通信失败")
    webSocket.close();
}

function isJson(str, pass_object) {
    if (pass_object && (Object.prototype.toString.call(str) === '[object Object]')) {
        return true;
    }
    if (!(Object.prototype.toString.call(str) === '[object String]')) {
        return false;
    }
    str = str.replace(/\s/g, '').replace(/\n|\r/, '');
    if (/^\{(.*?)\}$/.test(str)) {
        return /"(.*?)":(.*?)/g.test(str);
    }
    if (/^\[(.*?)\]$/.test(str)) {
        return str.replace(/^\[/, '')
            .replace(/\]$/, '')
            .replace(/},{/g, '}\n{')
            .split(/\n/)
            .map(function(s) {
                return this.tool_is_json(s);
            })
            .reduce(function(prev, curr) {
                return !!curr;
            });
    }
    return false;
}
